import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UDPTest {
    @Test
    public void testSender() {
        // 创建 DatagramSocket 实例
        try (DatagramSocket socket = new DatagramSocket()) {
            byte[] bytes = "我是发送端".getBytes(StandardCharsets.UTF_8);
            DatagramPacket datagramPacket = new DatagramPacket(
                    bytes, 0, bytes.length,
                    InetAddress.getByName("127.0.0.1"), 9090);
            // 发送数据包
            socket.send(datagramPacket);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void testReceiver() {
        byte[] bytes = new byte[1024 * 64];
        try (DatagramSocket datagramSocket = new DatagramSocket(9090)) {
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
            datagramSocket.receive(packet);
            String str = new String(packet.getData(), 0, packet.getLength());
            System.out.println(str);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
